<template>
  <el-row style="height: 100%; overflow-y: auto;overflow-x: hidden">
    <el-row class="add-title">
      <el-col :span="24">
        <i class="el-icon-arrow-left" @click="returnPage" />
        <span>修改知识-文章型</span>
      </el-col>
    </el-row>
    <el-divider />
    <el-row style="height: 100%">
      <el-form ref="myForm" :model="form" :rules="rules" label-width="100px" class="add-form">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" maxlength="30" />
        </el-form-item>
        <el-form-item label="封面和摘要">
          <el-row>
            <el-col :span="4" style="width: 150px;">
              <el-upload
                class="avatar-uploader"
                action="file"
                :show-file-list="false"
                accept="image/png, image/jpg, image/gif"
                :on-success="handleAvatarSuccess"
                :http-request="defaultAvatarUpload"
              >
                <img v-if="imageUrl" style="width: 150px;height: 150px" :src="imageUrl" class="avatar">
                <i v-else class="avatar-uploader-icon el-icon-circle-plus-outline">选择</i>
              </el-upload>
            </el-col>
            <el-col :span="20" style="width: calc(100% - 150px)">
              <el-input
                v-model="form.summary"
                type="textarea"
                placeholder="请输入摘要"
                style="height: 112px"
                resize="none"
                maxlength="300"
              />
              <el-row style="text-align: right">
                <el-button v-if="permission.aiSwitch" size="small" type="primary" @click="genAbstract">生成摘要</el-button>
              </el-row>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="关键字">
          <el-input v-model="form.keyWord" placeholder="请输入关键字,用英文逗号分隔" maxlength="100" />
        </el-form-item>
        <el-form-item label="内容">
          <mavon-editor
            ref="md"
            v-model="form.mdContent"
            style="min-height: 500px"
            :toolbars="markdownOption"
            @imgAdd="$imgAdd"
            @change="change"
          />
        </el-form-item>
        <el-form-item>
          <el-upload
            class="upload-demo"
            style="width: 100%"
            action="file"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :on-success="handleSuccess"
            :http-request="attachmentUpload"
            :before-upload="beforeFile"
            :file-list="fileList"
          >
            <el-button size="small" type="primary">点击上传附件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item style="text-align: center">
          <el-button v-if="permission.workbenchKbpSubmit" type="primary" @click="saveOrEdit(0)">提交审核</el-button>
          <el-button v-if="permission.workbenchKbpConfirm" type="primary" @click="saveOrEdit(1)">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <el-popover
      placement="right"
      trigger="click"
    >
      <el-row style="height: 100%; width: 100%">
        <el-form ref="myFormRight" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="知识目录" prop="categoryName">
            <el-select ref="parentTree" v-model="form.categoryName" clearable placeholder="选择目录" style="width: 80%">
              <el-option
                style="height: auto"
                :value="form.categoryName"
              >
                <el-tree
                  :data="treeData"
                  node-key="id"
                  default-expand-all
                  :expand-on-click-node="false"
                  @current-change="changeParent"
                />
              </el-option>
            </el-select>
          </el-form-item>
          <!--<el-form-item label="标签" multiple prop="knowledgeCategoryId">-->
          <!--<el-select multiple v-model="tags" placeholder="请选择" style="width: 80%">-->
          <!--<el-option v-for="tag in tagOption" :key="tag.value" :label="tag.label" :value="tag.value"></el-option>-->
          <!--</el-select>-->
          <!--<i class="el-icon-circle-plus-outline" style="cursor: pointer;font-size: 20px;color: #409EFF;margin-left: 10px"-->
          <!--@click="addTag"></i>-->
          <!--</el-form-item>-->
          <el-form-item label="有效期">
            <el-date-picker
              v-model="form.useStartTime"
              type="date"
              style="width: 80%"
              value-format="yyyy-MM-dd"
              placeholder="有效期开始"
              :picker-options="pickerOptions"
            />
            <el-date-picker
              v-model="form.useEndTime"
              type="date"
              style="width: 80%;margin-top: 15px"
              value-format="yyyy-MM-dd"
              placeholder="有效期结束"
              :picker-options="pickerOptions"
            />
          </el-form-item>
          <el-form-item label="置顶">
            <el-checkbox v-model="form.topStatus">在所在分类中置顶</el-checkbox>
          </el-form-item>
          <el-form-item v-show="isNotice" label="常见知识">
            <el-checkbox v-model="form.commonStatus">加入常见知识</el-checkbox>
          </el-form-item>
        </el-form>
      </el-row>
      <i slot="reference" class="el-icon-s-operation popoverIcon add-icon-fixed" />
    </el-popover>
    <el-dialog title="添加标签" :visible.sync="tagDialogFormVisibleArticle" append-to-body width="30%">
      <span>请输入标签</span>
      <el-input v-model="tagName" maxlength="5" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="tagDialogFormVisibleArticle = false">取 消</el-button>
        <el-button type="primary" @click="okAddTag">确 定</el-button>
      </div>
    </el-dialog>
  </el-row>
</template>

<script>
import { knowBussinessTree, articleSaveOrEdit, getArticleById, genAbstract, uploadFile } from '@/api/kbp'
import { mapGetters } from 'vuex'

export default {
  name: 'ArticleAdd',
  comments: {},
  components: {},
  data() {
    return {
      markdownOption: {
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: true, // 标记
        superscript: true, // 上角标
        subscript: true, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        code: true, // code
        table: true, // 表格
        fullscreen: true, // 全屏编辑
        readmodel: true, // 沉浸式阅读
        htmlcode: true, // 展示html源码
        help: true, // 帮助
        /* 1.3.5 */
        undo: true, // 上一步
        redo: true, // 下一步
        trash: true, // 清空
        /* 1.4.2 */
        navigation: true, // 导航目录
        /* 2.1.8 */
        alignleft: true, // 左对齐
        aligncenter: true, // 居中
        alignright: true, // 右对齐
        /* 2.2.1 */
        subfield: true, // 单双栏模式
        preview: true // 预览
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() <= Date.now() - (3600 * 1000 * 24)
        }
      },
      treeData: [],
      fileList: [],
      imageUrl: 'assets/theme/img/default.jpeg',
      form: {},
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ],
        categoryName: [
          { required: true, message: '请选择目录', trigger: 'blur' }
        ]
      },
      tagOption: [],
      tags: [],
      submitFileList: [],
      id: this.$route.query.id,
      tagDialogFormVisibleArticle: false,
      tagName: '',
      isNotice: false
    }
  },
  created() {

  },
  mounted() {

  },
  activated() {
    const that = this
    that.form = {}
    that.$set(that.form, 'topStatus', false)
    that.$set(that.form, 'commonStatus', false)
    that.id = that.$route.query.id
    // 是否显示加入常见知识
    if (that.$route.query.knowledgeType == 3) {
      that.isNotice = false
    } else {
      that.isNotice = true
    }
    that.initTreeData(that.$route.query.knowledgeType)
    that.initData()
  },
  computed: {
    ...mapGetters(['website', 'permission'])
  },
  methods: {
    /** ****************************  初始化数据  ************************************/
    // 初始化文章
    initData() {
      const that = this
      if (that.id) {
        getArticleById({ id: that.id }).then(res => {
          console.log('response get article data is: ' + JSON.stringify(res.data))
          that.form = res.data.data
          // 初始化标签
          if (that.form.tags) {
            const tagArr = that.form.tags.split(',')
            that.tags = tagArr
            that.tagOption = []
            if (tags.length) {
              for (const i in tagArr) {
                that.tagOption.push({ label: tagArr[i], value: tagArr[i] })
              }
            }
          }
          // 初始化封面
          if (that.form.coverImg) {
            that.imageUrl = window.CONFIG.fileServer + '/get?filename=' + that.form.coverImg
          } else {
            that.imageUrl = 'assets/theme/img/default.jpeg'
          }
          // 附件列表
          that.fileList = []
          if (that.form.knowledgeArticleFileList) {
            for (let j = 0; j < that.form.knowledgeArticleFileList.length; j++) {
              const file = that.form.knowledgeArticleFileList[j]
              that.fileList.push({ name: file.name, path: file.path })
            }
          }
          that.submitFileList = that.fileList
          // 置顶状态
          if (that.form.topStatus == 1) {
            that.form.topStatus = true
          }
          // 常见问题状态
          if (that.form.commonStatus == 1) {
            that.form.commonStatus = true
          }
        })
      }
    },
    // 初始化目录树
    initTreeData(type) {
      const that = this
      knowBussinessTree({ type: type }).then((res) => {
        console.log('response knowBussinessTree is: ' + JSON.stringify(res))
        if (res && res.data && res.data.data) {
          const data = res.data.data
          that.treeData = that.getTrees(data, 0)
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    getTrees(list, parentId) {
      const items = {}
      // 获取每个节点的直属子节点，*记住是直属，不是所有子节点
      for (let i = 0; i < list.length; i++) {
        if (list[i].name != window.Settings.hotCategory && list[i].name != window.Settings.commonCategory && list[i].name != window.Settings.businessCategory) {
          list[i].label = list[i].name
          const key = list[i].parentId
          if (items[key]) {
            items[key].push(list[i])
          } else {
            items[key] = []
            items[key].push(list[i])
          }
        }
      }
      return this.formatTree(items, parentId)
    },
    /**
       * 利用递归格式化每个节点
       */
    formatTree(items, parentId) {
      const result = []
      if (!items[parentId]) {
        return result
      }
      for (const t of items[parentId]) {
        t.children = this.formatTree(items, t.id)
        result.push(t)
      }
      return result
    },
    changeParent(data, node) {
      this.$refs.parentTree.visible = false
      this.$set(this.form, 'categoryName', data.label)
      this.$set(this.form, 'knowledgeCategoryId', data.id)
    },
    /** ****************************  其他  ************************************/
    returnPage() {
      const path = '/kbpDetail'
      this.$router.push({
        path: path,
        query: {
          id: this.id
        }
      })
    },
    cancel() {
      const path = '/kbpDetail'
      this.$router.push({
        path: path,
        query: {
          id: this.id
        }
      })
    },
    // 生成摘要
    genAbstract() {
      genAbstract({ content: this.form.content }).then(res => {
        console.log('response gen abstract data is: ' + JSON.stringify(res.data))
        if (res.data.code == 200) {
          this.$set(this.form, 'summary', res.data.data)
        }
      })
    },
    /** ****************************  上传附件  ************************************/
    // 上传附件前的处理
    beforeFile(file) {
      const fileType = file.type
      if (fileType === 'application/x-msdownload' || fileType === 'application/octet-stream') {
        this.$message({ message: '附件格式错误', type: 'warning' })
        return false
      }
      const isLt100M = file.size / 1024 / 1024 < 100 // 大小
      if (!isLt100M) {
        this.$message({ message: '附件大小不能超过100M', type: 'warning' })
        return false
      }
      return true
    },
    // 移出文件处理，fileList为移除后的文件列表
    handleRemove(file, fileList) {
      this.submitFileList = fileList
      this.fileList = fileList
      console.log('remove ' + JSON.stringify(this.submitFileList) + '&&' + JSON.stringify(this.fileList))
    },
    // 文件上传成功时的钩子
    handleSuccess(response, file, fileList) {
      this.submitFileList.push({ name: file.name, path: response.msg })
      console.log(JSON.stringify(this.submitFileList) + '&&' + JSON.stringify(this.fileList))
    },
    attachmentUpload($file) {
      const file = $file.file
      const filetype = file.name.substring(file.name.lastIndexOf('.') + 1)
      const formData = new FormData()
      formData['enctype'] = 'multipart/form-data'
      formData.append('file', file) // filename是键，file是值，就是要传的文件，test.zip是要传的文件名
      uploadFile(formData, filetype).then(response => {
        if (response && response.data) {
          this.submitFileList.push({ name: file.name, path: response.data })
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 删除文件之前的钩子
    beforeRemove(file, fileList) {

    },
    // 封面上传成功
    handleAvatarSuccess(res, file) {
      this.form.coverImg = res.msg
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    defaultAvatarUpload($file) {
      const file = $file.file
      const filetype = file.name.substring(file.name.lastIndexOf('.') + 1)
      const formData = new FormData()
      formData['enctype'] = 'multipart/form-data'
      formData.append('file', file) // filename是键，file是值，就是要传的文件，test.zip是要传的文件名
      uploadFile(formData, filetype).then(response => {
        if (response && response.data) {
          this.form.coverImg = response.data
          this.imageUrl = window.CONFIG.fileServer + '/get?filename=' + response.data
        }
      }).catch(error => {
        console.log(error)
      })
    },
    /** *************************  富文本编辑器mavon-editor  ******************************/
    // 所有操作都会被解析重新渲染
    change(value, render) {
      // render 为 markdown 解析后的结果[html]
      this.form.content = render
    },
    // 将图片上传到服务器，返回地址替换到md中
    $imgAdd(pos, $file) {
      const that = this
      const filetype = $file.name.substring($file.name.lastIndexOf('.') + 1)
      const formData = new FormData()
      formData['enctype'] = 'multipart/form-data'
      formData.append('file', $file) // filename是键，file是值，就是要传的文件，test.zip是要传的文件名
      uploadFile(formData, filetype).then(response => {
        if (response && response.data) {
          that.$refs.md.$img2Url(pos, window.CONFIG.fileServer + '/get?filename=' + response.data)
        }
      }).catch(error => {
        console.log(error)
      })
    },
    /** *****************************  提交审核  *******************************************/
    saveOrEdit(verifyStatus) {
      const that = this
      let myFormValid = false
      let myFormRightValid = false
      that.$refs['myForm'].validate((valid) => {
        if (valid) {
          myFormValid = true
        }
      })
      that.$refs['myFormRight'].validate((valid) => {
        if (valid) {
          myFormRightValid = true
        }
      })
      // 日期校验
      if (that.form.useStartTime && !that.form.useEndTime) {
        that.$message({ message: '请选择结束时间', type: 'warning' })
        return
      }
      if (!that.form.useStartTime && that.form.useEndTime) {
        that.$message({ message: '请选择开始时间', type: 'warning' })
        return
      }
      if (that.form.useStartTime && that.form.useEndTime) {
        var startTime = new Date(that.form.useStartTime).getTime()
        var useEndTime = new Date(that.form.useEndTime).getTime()
        if (useEndTime < startTime) {
          that.$message({ message: '结束时间不能早于开始时间', type: 'warning' })
          return
        }
      }
      // 校验通过
      if (myFormValid && myFormRightValid) {
        if (that.tags.length > 0) {
          that.form.tags = that.tags.join(',')
        }
        if (that.form.topStatus) {
          that.form.topStatus = '1'
        } else {
          that.form.topStatus = '0'
        }
        if (that.form.commonStatus) {
          that.form.commonStatus = '1'
        } else {
          that.form.commonStatus = '0'
        }
        that.form.submitFileList = that.submitFileList
        that.form.verifyStatus = verifyStatus
        if (!that.form.type) {
          that.form.type = that.$route.query.knowledgeType
        }
        articleSaveOrEdit(that.form).then(res => {
          console.log('response article save or edit data is: ' + JSON.stringify(res.data))
          if (res.data.code == 200) {
            if (verifyStatus == 0) {
              that.$message({ message: '提交成功,请到[我提交的]列表中查看审核状态', type: 'success' })
            } else {
              if (that.id) {
                that.$message({ message: '修改成功', type: 'success' })
              } else {
                that.$message({ message: '添加成功', type: 'success' })
              }
            }
            // 清空数据
            that.tagOption = []
            that.tags = []
            that.fileList = []
            that.submitFileList = []
            that.imageUrl = 'assets/theme/img/default.jpeg'
            that.form = {}
            that.$router.push({
              path: '/kbp'
            })
          } else if (res.data.code == 250) {
            that.$message({ message: '内容未发生改变，请重新输入！', type: 'info' })
          } else {

          }
        })
      }
    },
    /** *****************************  标签处理  *******************************************/
    okAddTag() {
      // 检测重复
      for (let i = 0; i < this.tags.length; i++) {
        if (this.tags[i] == this.tagName) {
          this.$message({ message: '标签已存在', type: 'warning' })
          return
        }
      }
      this.tagOption.push({ label: this.tagName, value: this.tagName })
      this.tags.push(this.tagName)
      this.tagDialogFormVisibleArticle = false
    },
    addTag() {
      if (this.tags.length >= 15) {
        this.$message({ message: '标签最多添加15个', type: 'warning' })
        return
      }
      this.tagName = ''
      this.tagDialogFormVisibleArticle = true
    }
  }
}
</script>

<style scoped>

  .add-title {
    font-weight: 700;
    font-size: 18px;
    padding-bottom: 5px
  }

  .add-title i {
    font-weight: 700;
    font-size: 18px;
    padding-bottom: 5px;
    cursor: pointer;
    padding-right: 10px
  }

  .add-form {
    padding-top: 10px;
  }

  /deep/ .el-divider--horizontal {
    margin: 4px 0
  }

  /deep/ .el-divider--vertical {
    height: 100%
  }

  /deep/ .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9 !important;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF !important
  }

  /deep/ .el-upload--text {
    width: 100% !important
  }

  .avatar-uploader-icon {
    font-size: 14px;
    color: rgb(49, 103, 175);
    width: 100%;
    height: 150px;
    line-height: 150px;
    text-align: center
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block
  }

  .add-icon-fixed {
    position: fixed;
    left: 1%;
    top: 36%;
    z-index: 999;
    font-size: 25px;
  }

  /deep/ .el-textarea__inner {
    height: 150px !important
  }

  /deep/ .el-card {
    height: 100% !important;
    overflow-y: auto
  }

  .el-select-dropdown__item {
    background-color: #0000 !important
  }

  .el-select-dropdown__item:hover {
    background-color: #0000 !important
  }

  .el-select-dropdown__item.selected {
    font-weight: normal
  }

  /deep/ .el-upload {
    text-align: unset !important
  }

  /deep/ .el-upload-list .el-upload-list__item{
    width: 50%;
    display: inline-block;
  }

</style>
